#include "stack.h"

void StackInit(Stack* ps)
{
	assert(ps);

	ps->_a = NULL;

	ps->_capacity = 0;

	ps->_top = -1;
}

void StackPush(Stack* ps, STDataType data)
{
	assert(ps);
	if (ps->_capacity - 1 == ps->_top)
	{
		int newcap = ps->_capacity == 0 ? MAX : ps->_capacity * 2;

		STDataType* tmp = (STDataType*)realloc(ps->_a, newcap*sizeof(STDataType));
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}

		ps->_capacity = newcap;
		ps->_a = tmp;
	}

	ps->_a[++ps->_top] = data;
}

void StackPop(Stack* ps)
{
	assert(ps);

	assert(!StackEmpty(ps));

	ps->_top--;
}

STDataType StackTop(Stack* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));

	return ps->_a[ps->_top];
}

int StackSize(Stack* ps)
{
	assert(ps);
	return ps->_top+1;
}

int StackEmpty(Stack* ps)
{
	assert(ps);

	return ps->_top==-1;
}

void StackDestroy(Stack* ps)
{
	assert(ps);

	free(ps->_a);
	ps->_a = NULL;

}


